﻿using System.Linq;
using System.Collections.Generic;
using System;
using Citi.Import.Util;

namespace Citi.GocAttributes.Domain
{
    public partial class Sid
    {
        private const string SidColumnName = "SID";

        public static readonly List<Definition<Sid>> Definitions = new List<Definition<Sid>>
            {
                new Definition<Sid> { ModelProperty = x => x.Description, MaxLength = 10, Required = true, ColumnName = SidColumnName, CustomConversionMethod = ValidateDescription}
            };

        private static object ValidateDescription(ref Sid model, string value, List<string> fields, ref string error, List<string> headers = null)
        {
            if (String.IsNullOrEmpty(value))
            {
                error = String.Format(ErrorFieldNull, SidColumnName);
                return Conversion.Validation.Failed;
            }

            var domain = CacheFacade.Get(SelectAll<Sid>).LastOrDefault(x => x.Description == value);

            if (domain != null)
            {
                model = domain;
                model.LastUpdate = DateTime.Now;
                return Conversion.Validation.Validated;
            }

            model.LastUpdate = DateTime.Now;
            model.ReferenceDate = DateTime.Today;
            return value;
        }

        public static void Save(IEnumerable<Sid> sids)
        {
            var toSave = sids.Distinct(new SidComparer()).Where(x => x != null && x.Id == 0).ToList();

            if (toSave.Any())
                toSave.First().Save(toSave, 100);

            CacheFacade.Clear(typeof(Sid));
        }

        public Sid SelectByDescription(string description)
        {
            return SelectAll<Sid>().FirstOrDefault(x => x.Description == description);
        }
    }

    public class SidComparer : IEqualityComparer<Sid>
    {
        public bool Equals(Sid x, Sid y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
                return false;

            return x.Description == y.Description && x.Id == y.Id;
        }

        public int GetHashCode(Sid item)
        {
            if (ReferenceEquals(item, null)) return 0;

            var hashDescription = item.Description == null ? 0 : item.Description.GetHashCode();
            var hashId = item.Description == null ? 0 : item.Id.GetHashCode();

            return hashDescription ^ hashId;
        }
    }
}
